//global variables
var stage2 = new createjs.Stage( "canvas-intro" );
var stage = new createjs.Stage( "canvas-main" );
var stage3 = new createjs.Stage( "canvas-outcome" );

var score;
var scoreText;
var binText;
var attempts;
var attemptText;
var levelText;
var NUMBER_OF_POLE_LINES = 3;

var initialPositionX = 10;
var initialPositionY = 520;
var initialVelocityX;
var initialVelocityY;

//width and heights of bitmaps
var width = 87;
var width2 = 97;
var height = 100;
var height2 = 75;

var loadingBar;
var progressValue = 0;
var progressText;

var queue;
var manifest = [ { id: "boy", src: "images/boy.png" },
                 { id: "paperball", src: "images/paperball2.png" },
                 { id: "classroom", src: "images/classroom3.jpg" },
                 { id: "background", src: "images/MyPhoto3.jpg" } ];

var LOADING_BAR_WIDTH = 600;
var LOADING_BAR_HEIGHT = 40;

var timestep = 0;
var delta = .3;

var binContainers = new Array();
var binsImage;
var binsContainer;
var numberOfBins;

var background = new Image();
background.src = "images/classroom3.jpg";
var backgroundContainer;

var background2 = new Image();
background2.src = "images/MyPhoto3.jpg"
var background2Container;

var paperball = new Image();
paperball.src = "images/paperball2.png";
var paperballContainer;

var boy = new Image();
boy.src = "images/boy2.png";
var boyContainer;

var game = new Game();
game.resetGame();
game.setLevel( 1 );
game.setGameLevel();

//initialize the bins based on level

function init()
{
        document.getElementById( "velocity" ).style.display = "none";
        document.getElementById( "loading" ).play();
        var stage = new createjs.Stage( "canvas-intro" );
       
        
        background2Container = new createjs.Bitmap( background2 );
        background2Container.x = 0;
        background2Container.y = 0;
        
       stage2.addChild( background2Container );
        
        var rules = new createjs.Text( "Velocity is a term used to describe the rate of change of the position of an object. \n " + 
                        "For example if you are throwing a baseball to first base, the velocity  " +
                        "is calculated  \n by how fast you throw and in what direction you throw. Velocity is a very scientific \n " +
                        "measurement. With this game you will be able to practice your calculations of velocity by \n " +
                         "throwing a paper wad into the trash basket. You will need to input the x and y coordinates \n " +
                        "in order to calculate the velocity and get the paper wad into the waste basket." ,
                     "20px Serif", "red" );
        rules.textAlign = "left";
        rules.x = 125;
        rules.y = 50;
        
        stage2.addChild( rules );
        
        //code for the play button container on the welcome/introduction canvas
        var containerPlayButton = new createjs.Container();
        
        var playButton = new createjs.Shape();
        playButton.graphics.setStrokeStyle( "2" );
        playButton.graphics.beginStroke( "red" );
        playButton.graphics.beginFill( "yellow" );
        playButton.graphics.drawRoundRect( 0, 0, 200, 75, 20 );
        
        var playText = new createjs.Text( "Click to Play", "30px Serif", "Red" );
        playText.textAlign = "center";
        playText.x = 200 / 2;
        playText.y = 30 / 2;
        
        containerPlayButton.x = 100;
        containerPlayButton.y = 300;
        
        containerPlayButton.addChild( playButton, playText );
        containerPlayButton.addEventListener( "click", playButtonClick );
        
        stage2.addChild( containerPlayButton );
        
        progressText = new createjs.Text( progressValue + "%", "18px Serif", "red" );
		progressText.textAlign = "center";
		progressText.x = 875;
		progressText.y = 600;
	
	stage2.addChild( progressText );
	
	var bar = new createjs.Shape();
	bar.graphics.setStrokeStyle( "2" );
	bar.graphics.beginStroke( "black" );
	bar.graphics.drawRect( 0, 0, LOADING_BAR_WIDTH, LOADING_BAR_HEIGHT );
	
	var barContainer = new createjs.Container();
	barContainer.addChild( bar );
	barContainer.x = stage2.canvas.width / 2 - LOADING_BAR_WIDTH / 2;
	barContainer.y = 600;
		
	stage2.addChild( barContainer );
	
	loadingBar = new createjs.Shape();
	loadingBar.graphics.beginFill( "red" );
	loadingBar.graphics.drawRect( stage2.canvas.width / 2 - LOADING_BAR_WIDTH / 2, 475, 0, LOADING_BAR_HEIGHT );
	stage2.addChild( loadingBar );
	
	stage2.update();
	
}
	
function preload()
{
	init();
	stage.update();
	
	queue = new createjs.LoadQueue( false );
	
	queue.addEventListener( "fileload", handleFileLoad );
	//queue.addEventListener( "complete", handleComplete );
	
	queue.loadManifest( manifest );
	
	queue.load();
}

function handleFileLoad( evt )
{
	var totalProgress = manifest.length;
	
	progressValue = progressValue + 1;
	
	var percentage = Math.ceil( ( progressValue / totalProgress * 100 ) );
	progressText.text = percentage + "% Loaded";
	
	loadingBar.graphics.beginFill( "blue" );
	loadingBar.graphics.drawRect( stage2.canvas.width / 2 - LOADING_BAR_WIDTH / 2, 600, percentage / 100 * LOADING_BAR_WIDTH, LOADING_BAR_HEIGHT );
	stage2.update();
}


//when the play button is clicked on the welcome canvas, the intro canvas is hidden and the main canvas is displayed
function playButtonClick( evt )
{
        document.getElementById( "canvas-main" ).style.display = "inline";
        document.getElementById( "canvas-intro" ).style.display = "none";
        drawMainCanvas();
        
}

//code for the second canvas, the main canvas where everything is played
function drawMainCanvas()
{
		stage.removeAllChildren();
		stage.update();
        initBinContainers();
        drawBackground();
        drawGameStats();
        
        //adds the astronaut image to the main-canvas
        paperballContainer = new createjs.Bitmap( paperball );

        paperballContainer.x = initialPositionX;
        paperballContainer.y = initialPositionY;
        
        //adds the foreground image of a planet
        boyContainer = new createjs.Bitmap( boy );
        boyContainer.x = 100;
        boyContainer.y = 425;
        
        //create the container for the poles lines.
        drawPoleAndBin();

        stage.addChild( boyContainer, paperballContainer );
        stage.update();
}


//draws the background image first
function drawBackground()
{
        backgroundContainer = new createjs.Bitmap( background );
        backgroundContainer.x = 0;
        backgroundContainer.y = 0;
        
        stage.addChild( backgroundContainer );
}

function drawGameStats()
{
		
        scoreText = new createjs.Text( "Score: " + game.getScore(), "22px Serif", "red");
        scoreText.textAlign = "left";
        
        var scoreContainer = new createjs.Container();
        scoreContainer.x = 10;
        scoreContainer.y = 10;
        scoreContainer.addChild( scoreText );
        
    	binText = new createjs.Text( "Bins Remaining: " + game.getNumberOfBins(), "18px Serif", "red" );
		binText.textAlign = "left";
	
		var binTextContainer = new createjs.Container();
		binTextContainer.x = 160;
		binTextContainer.y = 50;
		binTextContainer.addChild( binText );
        
        levelText = new createjs.Text( "Level: " + game.getLevel(), "22px Serif",  "red");
        levelText.textAlign = "left";
        
        
        var levelContainer = new createjs.Container();
        levelContainer.x = 10;
        levelContainer.y = 30;
        levelContainer.addChild( levelText );
        
        attemptText = new createjs.Text( "Attempts: " + game.getAttempts(), "22px Serif", "red");
        attemptText.textAlign = "left";
        
        var attemptContainer = new createjs.Container();
        attemptContainer.x = 10;
        attemptContainer.y = 50;
        attemptContainer.addChild( attemptText );
        
        var formBox = new createjs.DOMElement( "velocity" );
        document.getElementById( "velocity" ).style.display = "inline";
        formBox.x = 50;
        formBox.y = 300;
        
        stage.addChild( scoreContainer, levelContainer, attemptContainer, formBox );
}

function initBinContainers()
{
	//drawing the satellites
	numberOfBins = game.getNumberOfBins();
	var startingX = 450;
	//distances between orbit lines
	var intervalX = Math.floor( (stage.canvas.width - startingX ) / NUMBER_OF_POLE_LINES - 75 );
	
	for( i = 0; i < numberOfBins; i = i + 1 )
		{
			//draw the satellites
			var bins = new Image();
			bins.src = "images/trashcan.png";
			binsImage = new createjs.Bitmap( bins );
			binsContainer = new createjs.Container();
			binsContainer.x = startingX + intervalX * i - 50 + 7.5;
			binsContainer.y = game.getBinHeights()[ i ];
			
			var binsShape = new createjs.Shape();
			binsShape.graphics.setStrokeStyle( "1" );
			binsShape.graphics.beginStroke( "red" );
			binsShape.graphics.drawRect( 0, 0, width2, height2 );
			
			binsContainer.addChild( binsImage, binsShape );

			binContainers.push( binsContainer );
		}	
}
//Function to draw the pole lines and bins after the game level has loaded
function drawPoleAndBin()
{
        var numberOfBins = game.getNumberOfBins();
        var startingX = 450;
        
        var intervalX = Math.floor( (stage.canvas.width - startingX ) / NUMBER_OF_POLE_LINES - 75 );
        
        for( i = 0; i < numberOfBins; i = i + 1 )
                {
                        if( game.getBinHeights()[ i ] != -1 )
                                {
                                        //Draw the pole lines
                                        var pole = new createjs.Shape();
                                        pole.graphics.beginLinearGradientFill( [ "gray", "#FF0000", "gray" ], [ 0, .5, 1 ], startingX + intervalX * i, 0, startingX + intervalX * i + 10, 0 );
                                        pole.graphics.drawRect( startingX + intervalX * i, 0, 10, stage.canvas.height );
                                        
                                        stage.addChild( pole );
                                        
                                        //Draw the bins
                                        var bins = new Image();
                                        bins.src = "images/trashcan.png";
                                        var binsContainer = new createjs.Bitmap( bins );
                                        binsContainer.x = startingX + intervalX * i - 50 + 7.5;
                                        binsContainer.y = game.getBinHeights()[ i ];
                                        
                                        stage.addChild( binsContainer );
                                }
                }
        stage.update();
}
//function to redraw the canvas
function redraw()
{
        stage.removeAllChildren();
        drawBackground();
        drawGameStats();
        drawPoleAndBin();
        stage.addChild( boyContainer, paperballContainer );
        stage.update();
}
//the new two function detail what happens as the launch button is clicked.
createjs.Ticker.setFPS( 24 );

function isIntersect()
{
	if( paperballContainer.x < binsContainer.x + width2 &&
			paperballContainer.x + width > binsContainer.x &&
			paperballContainer.y < binsContainer.y + height2 &&
			paperballContainer.y + height > binsContainer.y )
		{
			return true;
		}
	
	
	
}

function tick()
{
	initialVelocityX = document.getElementById( "valueX" ).value;
	initialVelocityY = document.getElementById( "valueY" ).value;
	
	paperballContainer.x = initialPositionX + initialVelocityX * timestep;
	paperballContainer.y = initialPositionY + initialVelocityY * timestep + .5 * 9.81 * timestep * timestep;
	
	timestep = timestep + delta;
	
	boyContainer.y -= 2;
	//boyContainer.x += 2;
	
	
	//check collision here//
	
	if( isIntersect() )
		{
			var score = game.getScore();
			game.setScore( score + BIN_POINTS );
			scoreText.text = "Score: " + game.getScore();
			
		}

	

	redraw();
	
		
	if( paperballContainer.y > stage.canvas.height || paperballContainer.x > stage.canvas.width )
		{
			createjs.Ticker.removeListener( this );
			document.getElementById( "miss" ).play();
			paperballContainer.x = initialPositionX;
			paperballContainer.y = initialPositionY;
			timestep = 0;
		}
	stage.update();
}

var binNumber;
var currentBin;
function isIntersect()
{
	binNumber = binContainers.length - 1;
		
	for( var i = binNumber; i >= 0; i = i - 1 )
		{
			currentBin = binContainers[ i ];
			if( paperballContainer.x < binContainers[ i ].x + width2 &&
					paperballContainer.x + width > binContainers[ i ].x &&
					paperballContainer.y < binContainers[ i ].y + height2 &&
					paperballContainer.y + height > binContainers[ i ].y )
				{
					stage.removeChild( currentBin );
					binContainers.splice( i, 1 );
					document.getElementById( "hit" ).play();
					console.log( game.getNumberOfBins() + "," + binNumber );
					//binText.text = "Bins Remaining: " + binNumber;
					stage.update();
					
					var levelNumber = game.getLevel();
					if( binNumber == 0 )
						{
							game.setLevel( levelNumber + 1);
							game.setGameLevel();
							game.checkGameStatus();
							stage.removeAllChildren();
							stage.update();
							initBinContainers();
							drawPoleAndBin();
							createjs.Ticker.removeListener( this );
							paperballContainer.x = initialPositionX;
							paperballContainer.y = initialPositionY;
							timestep = 0;
						}
					return true;
				}
			binNumber = binContainers.length - 1;
		}	
	return false;
}

//function to be called onclick that starts the animation and adjusts the attempts
function launch()
{
	var numberOfAttempts = game.getAttempts();
	if( numberOfAttempts > 0 )
		{
			game.setAttempts( numberOfAttempts - 1 );
			attemptText.text = "Attempts: " + game.getAttempts();
			createjs.Ticker.addListener( this );
		}
	else 
		{
			createjs.Ticker.removeListener( this );
			game.checkGameStatus();
		}
	stage.update();
}


//code for the third canvas, the outcome where winner and/or loser is displayed
function drawOutcomeCanvas()
{
		stage.removeAllChildren();
		stage.update();
		document.getElementById( "gameover" ).play();
        document.getElementById( "velocity" ).style.display = "none";
         document.getElementById( "canvas-outcome" ).style.display = "inline";
        document.getElementById( "canvas-main" ).style.display = "none";
       
        
       
        background2Container;
        
        
        
        
        var outcomeText = new createjs.Text( "You were unable to calculate the Velocity. \n The classroom is dirty! \n", "40px Serif", "red" );
        outcomeText.text += "Game Over!!";
        outcomeText.textAlign = "center";
        outcomeText.x = 500;
        outcomeText.y = 50;
        
       
        
     
        
        stage3.addChild( background2Container, outcomeText );
        stage3.update();
        
}
//code for winner canvas
function drawWinnerCanvas()
{
	stage3.removeAllChildren();
	stage3.update();
	document.getElementById( "winner" ).play();
	document.getElementById( "velocity" ).style.display = "none";
	document.getElementById( "canvas-outcome" ).style.display = "inline";
	document.getElementById( "canvas-main" ).style.display = "none";
	

	
	background2Container;
	
	var outcomeWText = new createjs.Text( "You have calculated the velocity! \n Thank you for keeping the class clean!\n", "40px Serif", "red" );
	outcomeWText.text += "Winner!!";
	outcomeWText.textAlign = "center";
	outcomeWText.x = 500;
	outcomeWText.y = 50;
	
	stage3.addChild( background2Container, outcomeWText );
	stage3.update();	
}



//code generated in collaboration with Amber and Affraa  
